<template>
  <div class="layout-container test-sample-data-dialog"  v-loading="loading">
    <el-tabs
      :tab-position="tabPosition"
      class="demo-tabs"
      v-model="activeName"
      @tab-change="onHandleClick"
    >
      <el-tab-pane label="试验场景说明描述项" name="first">
        <TestSceneDescriptTab
          ref="firstRef"
          :interferType="interferType"
          :dataSourceObject="dataSourceObject"
        />
        <!-- 试验场景说明描述项 -->
      </el-tab-pane>
      <el-tab-pane label="战技信息描述项" name="second">
        <TactInfoDescriptTab
          ref="secondRef"
          :interferType="interferType"
          :dataSourceObject="dataSourceObject"
        />
      </el-tab-pane>
    </el-tabs>

    <div class="buttons-group common-buttons">
      <el-button type="primary" @click="onHandleDealData" v-if="!disabled"
        >进行数据处理</el-button
      >
      <el-upload
        action=""
        class="upload-demo"
        :show-file-list="false"
        accept=".json"
        :http-request="onUploadJSonFile"
      >
        <el-button type="primary" v-if="!disabled">手动导入json</el-button>
      </el-upload>
      <el-button type="primary" @click="onBack">返回</el-button>
    </div>

    <span class="base-info-button" @click="onBaseInfo">基础信息</span>

    <BaseInfoForm
      v-if="visible"
      ref="baseInfoRef"
      @onInterferTypeValue="onInterferTypeValue"
      :onClose="onClose"
      :sampleBaseInfoVO="baseInfo"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, provide, reactive, ref, watch } from 'vue';
import { TabsInstance, ElMessage, ElMessageBox } from 'element-plus';
import TestSceneDescriptTab from './TestSceneExplainDescriptItem/index.vue';
import TactInfoDescriptTab from './TactInfoDescriptItem/index.vue';
import BaseInfoForm from './BaseInfoForm/index.vue';
import { useRoute, useRouter } from 'vue-router';
import { reverseContentType } from '@/utils/tools';
import { httpDealData, getSampleDataInfo } from '@/api/testSampleData';

let $router = useRouter();
const route = useRoute();
const layerType = route.query.layerType;
const oldSampleId = route.query.oldSampleId
const isLook = layerType === 'look' ? true : false;
const disabled = ref<boolean>(isLook);
const loading = ref<boolean>(false)

// 手动导入json字符串存储的数据
const dataSourceObject = ref<Object>({});
const baseInfo = ref<Object>({});
const tabPosition = ref<TabsInstance['tabPosition']>('left');
const activeName = ref<string>('first');
const visible = ref<boolean>(false);
const baseInfoRef = ref();
// 干扰类型默认为: 舰载有源干扰-雷达
const interferType = ref<string>('舰载有源干扰-雷达');

const firstRef = ref();
const secondRef = ref();

onMounted(() => {
  if (
    layerType === 'look' ||
    layerType === 'edit' ||
    layerType === 'comparison' ||
    oldSampleId
  ) {
    getSampleDetail();
  } else {
    baseInfo.value = JSON.parse(sessionStorage.getItem('baseInfoVO'));
  }
  interferType.value = route.query.interType;
});

// 获取试验样本详情
const getSampleDetail = () => {
  let params = {  }
  if(oldSampleId) {
    // 基于原有的试验样本更改数据：使用原有的样本id查询详情
    params = { sampleId: oldSampleId }
  } else {
    params = { sampleId: route.query.sampleId }
  }
  loading.value = true
  getSampleDataInfo(params).then((res: any) => {
    loading.value = false
    const { code, data } = res;
    if (code === 200) {
      dataSourceObject.value = data;
      baseInfo.value = data.sampleBaseInfoVO;
    }
  });
};

// tab页签切换
const onHandleClick = (TabPaneName: string) => {
  activeName.value = TabPaneName;
};

// 基础信息按钮收缩事件
const onBaseInfo = () => {
  visible.value = true;
};

// 父组件拿到子组件干扰类型的值
const onInterferTypeValue = (value: string) => {
  interferType.value = value;
};

// 进行数据处理
const onHandleDealData = async () => {
  const isValidate = await firstRef.value.validateFieldFun();
  const isValidate2 = await secondRef.value.validateFieldFun();
  if (isValidate || isValidate2) {
    ElMessageBox.confirm('请检查是否有必填项未填写!', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).catch(() => {});
    return
  }
  
  ElMessageBox.confirm(
    '你确定要进行数据处理?, 数据处理前请先保存所有的数据',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const params = reverseContentType({ sampleId: route.query.sampleId });
      loading.value = true
      httpDealData(params).then((res: any) => {
        const { code, data, message } = res;
        loading.value = false
        if (code === 200) {
          ElMessage({
            message: message || '数据处理成功',
            type: 'success',
          });
          $router.push({
            path: '/testSampleDataManageSystem/testSampleData/comparison',
            query: {
              dealBeforeId: route.query.sampleId,
              dealAfterId: data.data[0],
              interType: route.query.interType,
            },
          });
        }
      });
    })
    .catch(() => {});
};

// 导入json数据
const onUploadJSonFile = (options: any) => {
  guestKeywordUpload(options);
};

const guestKeywordUpload = (options: any) => {
  const { file } = options;
  if (file.type !== 'application/json') {
    return ElMessage({
      message: '请上传JSON格式的文件',
      type: 'warning',
    });
  }
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = function () {
    const json = JSON.parse(reader.result);
    dataSourceObject.value = json;
  };
};

// 返回
const onBack = () => {
  sessionStorage.removeItem('baseInfoVO');
  // 试验样本数据页面
  $router.push({
    path: '/testSampleDataManageSystem/testSampleData',
    query: {},
  });
  
};

// 关闭
const onClose = () => {
  visible.value = false;
};
</script>

<style lang="scss">
@import '@/assets/style/buttons';
@import '@/assets/style/tabs';
.test-sample-data-dialog {
  position: relative;
  .buttons-group {
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0px 0px 10px rgba(218, 222, 224, 1);
    padding: 10px 0;
  }
  .upload-demo {
    margin: 0 10px;
  }

  .base-info-button {
    position: absolute;
    border-radius: 6px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.15);
    right: 80px;
    top: 15px;
    padding: 5px 10px;
    cursor: pointer;
    font-size: 14px;
    color: rgb(1, 18, 90);
  }

  :deep() {
    .modalClass {
      position: absolute;
      right: 22px;
      top: -25px;
    }
    .el-dialog__header {
      border-bottom: 1px solid rgba(221, 221, 221, 1);
      margin-bottom: 15px;
      padding-bottom: 10px;
      margin-right: 0px;
      padding: 10px;
    }
    .el-dialog__title {
      font-size: 15px;
      color: rgba(1, 18, 90, 1);
    }
    .el-dialog__headerbtn {
      top: -2px;
    }
    .el-dialog__body {
      padding: 0px;
    }
  }
}
</style>
